import React from 'react';
import Taro from '@tarojs/taro';
import { render, unmountComponentAtNode } from '@tarojs/react';
import { document, } from '@tarojs/runtime';
import { View } from '@tarojs/components';
import styles from "./index.module.scss";
import cName from 'classnames'
import { getMenuButtonBoundingClientRectCompat } from '@/utils/common';

const DemoNotify = (props: INotifyProps) => {
    const { type = 'primary', msg = '消息提示', top } = props;

    // 获取系统信息
    const systemInfo = Taro.getSystemInfoSync();
    // 获取状态栏高度
    const statusBarHeight = systemInfo.statusBarHeight || 0;
    // 获取胶囊按钮位置信息
    const menuButtonInfo = getMenuButtonBoundingClientRectCompat();
    const menuButtonTop = menuButtonInfo.top;
    const menuButtonHeight = menuButtonInfo.height;
    const navbarHeight =
        (menuButtonTop - statusBarHeight) * 2 + menuButtonHeight;

    return (
        <View
            className={cName(styles['base-nofity-wrapper'], styles[`nofity-${type}`])}
            style={{ position: 'fixed', top: `${props?.top ? top : (navbarHeight + menuButtonTop)}px` }}
        >
            {msg}
        </View>
    );
};


export const show = (props: INotifyProps) => {

    const { duration = 3000, onClose = () => { } } = props;

    const view = document.createElement('view')
    view.id = '__toast'

    const currentPages = Taro.getCurrentPages()
    const currentPage = currentPages[currentPages.length - 1] // 获取当前页面对象
    const path = currentPage.$taroPath
    const pageElement = document.getElementById(path)

    render(<DemoNotify {...props} />, view)
    pageElement?.appendChild(view)

    if (duration !== 0) {
        setTimeout(() => {
            onClose?.();
            destroyToast(view);
        }, duration)
    }

    if (duration === 0) {
        return destroyToast.bind(null, view)
    }
}

export const destroyToast = (node) => {
    const currentPages = Taro.getCurrentPages()
    const currentPage = currentPages[currentPages.length - 1]
    const path = currentPage.$taroPath
    const pageElement = document.getElementById(path)

    unmountComponentAtNode(node)
    pageElement?.removeChild(node)
}
